package com.jn.zhinongbao.adapter;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.supportingagriculturaltreasures.adapter.ChatMessageAdapter;
import com.example.supportingagriculturaltreasures.bean.ChatMessage;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.ChatManager;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

import java.util.List;

/**
 * 聊天界面
 */
public class ChatActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText etMessage;
    private ImageButton btnSend;
    
    private ChatMessageAdapter adapter;
    private ChatManager chatManager;
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    
    private String chatRoomId;
    private String otherUserName;
    private int otherUserId;
    private int currentUserId;
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        initData();
        initViews();
        setupRecyclerView();
        loadMessages();
        setupClickListeners();
    }

    private void initData() {
        chatManager = ChatManager.getInstance(this);
        preferenceManager = new PreferenceManager(this);
        databaseHelper = new DatabaseHelper(this);
        
        currentUserId = preferenceManager.getCurrentUserId();
        currentUser = databaseHelper.getUserById(currentUserId);
        
        // 获取Intent传递的数据
        chatRoomId = getIntent().getStringExtra("chat_room_id");
        otherUserName = getIntent().getStringExtra("other_user_name");
        otherUserId = getIntent().getIntExtra("other_user_id", -1);
        
        if (currentUser == null || chatRoomId == null || otherUserId == -1) {
            Toast.makeText(this, "聊天数据错误", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(otherUserName);
        }

        recyclerView = findViewById(R.id.recycler_view);
        etMessage = findViewById(R.id.et_message);
        btnSend = findViewById(R.id.btn_send);
    }

    private void setupRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true); // 从底部开始堆叠，方便显示最新消息
        recyclerView.setLayoutManager(layoutManager);
        
        adapter = new ChatMessageAdapter(this, null);
        recyclerView.setAdapter(adapter);
    }

    private void loadMessages() {
        List<ChatMessage> messages = chatManager.getChatMessages(chatRoomId, currentUserId);
        adapter.updateMessages(messages);
        
        // 滚动到最底部
        if (!messages.isEmpty()) {
            recyclerView.scrollToPosition(messages.size() - 1);
        }
        
        // 标记消息为已读
        chatManager.markMessagesAsRead(chatRoomId, currentUserId);
    }

    private void setupClickListeners() {
        btnSend.setOnClickListener(v -> sendMessage());
        
        // 监听输入框变化，控制发送按钮状态
        etMessage.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                btnSend.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
            }

            @Override
            public void afterTextChanged(android.text.Editable s) {}
        });
    }

    private void sendMessage() {
        String content = etMessage.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "请输入消息内容", Toast.LENGTH_SHORT).show();
            return;
        }

        // 发送消息
        boolean success = chatManager.sendMessage(chatRoomId, currentUserId, content);
        if (success) {
            // 清空输入框
            etMessage.setText("");
            
            // 刷新消息列表
            loadMessages();
        } else {
            Toast.makeText(this, "消息发送失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 页面销毁时标记消息为已读
        if (chatRoomId != null) {
            chatManager.markMessagesAsRead(chatRoomId, currentUserId);
        }
    }
} 